import type { RouterRes } from '@/api/types';
import type { RouteComponent } from 'vue-router';
import { localRouteRecordRaw } from '@/router/routes/types';
// import auth from '@/plugins/auth';
// import Layout from '@/layout/index';
// import ParentView from '@/components/ParentView';
// import InnerLink from '@/layout/components/InnerLink';
// 将所有子路由提升至一个级

const modules = import.meta.glob('@/views/**/*.vue');
const DEFAULT_LAYOUT = () => import('@/layout/default-layout.vue');
const NOT_FOUND = () => import('@/views/not-found/index.vue');
function handleChildren(childrenMap: Array<RouterRes>, lastRouter?: RouterRes) {
  let children: Array<RouterRes> = [];
  childrenMap.forEach((el) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach((c) => {
          c.path = `${el.path}/${c.path}`;
          if (c.children && c.children.length) {
            children = children.concat(handleChildren(c.children, c));
            return;
          }
          children.push(c);
        });
        return;
      }
    }
    if (lastRouter) {
      el.path = `${lastRouter.path}/${el.path}`;
    }
    children = children.concat(el);
  });
  return children;
}

const loadView = (view: string): RouteComponent => {
  let res: RouteComponent = NOT_FOUND;
  const keys = Object.keys(modules);
  keys.forEach((path) => {
    const dir = path.split('views/')[1].split('.vue')[0];
    if (dir === view) {
      res = () => modules[path]();
    }
  });
  return res;
};

// 遍历后台传来的路由字符串，转换为组件对象，promote：控制提升子路由到一个级
export function handleAsyncRouter(
  asyncRouter: Array<RouterRes>,
  promote = false
) {
  return asyncRouter.map((route) => {
    const routeRecord: localRouteRecordRaw = {
      name: route.name,
      component: NOT_FOUND,
      path: route.path,
      meta: route.meta,
      hidden: route.hidden,
      children: [],
      alwaysShow: route.alwaysShow,
    };
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        routeRecord.component = DEFAULT_LAYOUT;
      } else if (route.component === 'ParentView') {
        routeRecord.component = DEFAULT_LAYOUT;
      } else if (route.component === 'InnerLink') {
        routeRecord.component = DEFAULT_LAYOUT;
      } else {
        routeRecord.component = loadView(route.component);
      }
    }
    if (promote && route.children) {
      // 将子级路由提升到一个级
      route.children = handleChildren(route.children);
    }
    if (route.children && route.children.length) {
      routeRecord.children = handleAsyncRouter(route.children, promote);
      routeRecord.redirect = route.redirect;
    }
    return routeRecord;
  });
}

/**
 * 字符权限校验
 * @param {Array} value 校验值
 * @returns {Boolean}
 */
export function checkPermi(
  value: Array<string>,
  permissions: string[]
): boolean {
  if (value && value.length > 0) {
    const permissionDatas = value;
    const allPermission = '*:*:*';

    const hasPermission = permissions.some((permission) => {
      return (
        allPermission === permission || permissionDatas.includes(permission)
      );
    });
    if (!hasPermission) {
      return false;
    }
    return true;
  }
  return false;
}

/**
 * 角色权限校验
 * @param {Array} value 校验值
 * @returns {Boolean}
 */
export function checkRole(value: Array<string>, roles: string[]): boolean {
  if (value && value.length > 0) {
    const permissionRoles = value;
    const superAdmin = 'admin';

    const hasRole = roles.some((role) => {
      return superAdmin === role || permissionRoles.includes(role);
    });

    if (!hasRole) {
      return false;
    }
    return true;
  }
  return false;
}

// 路由遍历，验证是否具备权限
export function filterLocalPermissonRoutes(
  routes: Array<localRouteRecordRaw>,
  permissions: string[],
  roles: string[]
) {
  const res: Array<localRouteRecordRaw> = [];
  routes.forEach((route) => {
    if (route.permissions) {
      if (checkPermi(route.permissions, permissions)) {
        res.push(route);
      }
    } else if (route.roles) {
      if (checkRole(route.roles, roles)) {
        res.push(route);
      }
    }
  });
  return res;
}
